
from neat import config, population, chromosome, genome, visualize
#from neat import ctrnn
from neat.nn import nn_cpp	 as nn
import math, random
import cPickle as pickle
import time
import gtk
from visualisewidget3d import VisualiseWidget3D


def evaluate_population(population):

	for chromo in population:
		net = nn.create_ffphenotype(chromo)
		
		from simulator import Simulator
		from environment import Environment
		from robot import Robot
		from brain import Brain
		robot = Robot(Brain(net))
		environment = Environment()
		sim = Simulator(robot, environment)
		
		stepmax = 15 * 6.0
		stepcount = 0
		while stepcount < stepmax:
			sim.step()
			
			#x = sim.reference.position_x
			#robopos = sim.robot.torso.getPosition()
			
			#if robopos[0] < x - 0.3 or robopos[0] > x + 0.2 or robopos[1] < 1.05:
			#	break
				
			stepcount += 1
		
		fitness = sim.get_fitness()
		if fitness < 0:
			fitness = 0
		chromo.fitness = fitness


if __name__ == "__main__":

	
	config.load('evolve_config') 

	chromosome.node_gene_type = genome.CTNodeGene #CT

	population.Population.evaluate = evaluate_population
	pop = population.Population()
	pop.epoch(1, report=1, save_best=0)

	print 'Number of evaluations: %d' %(pop.stats[0][-1]).id

	winner = pop.stats[0][-1]
	net = nn.create_ffphenotype(winner)
	

	window = gtk.Window()
	vw = VisualiseWidget3D(save_video = False)
	window.add(vw)
	window.connect("destroy", gtk.main_quit)
	window.show_all()

	from simulator import Simulator
	from environment import Environment
	from robot import Robot
	from brain import Brain
	robot = Robot(Brain(net))
	environment = Environment()
	sim = Simulator(robot, environment, vw)
	vw.simulator = sim

	from timer import SimStepper
	c = SimStepper()
	c.functions.append(sim.step)
	c.start()	
	gtk.main()	
	c.stop()
	
	c = None
	vw = None
	
	#print pop.stats[0][-1]
